/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    //序列化
    char* Serialize(TreeNode *root) {    
        string str;
        dfs1(root, str); //先序遍历
        char *p=new char[str.size()+1];
        strcpy(p, str.c_str());
        return p;
    }
    void dfs1(TreeNode *root,string &str)
    {
        if(root==nullptr)
        { 
            str+="#,";
            return;
        }
        str+=to_string(root->val)+",";
        dfs1(root->left, str);
        dfs1(root->right, str);
    }
    //反序列化
    TreeNode* Deserialize(char *str) {
        int dex=0;
        return dfs2(str, dex);
    }
    TreeNode* dfs2(char *str,int &index)
    {
        int len=index;
        while(str[len]!=',')
            len++;
        if(str[index]=='#')
        {
            index=len+1;
            return nullptr;
        }
        int num=0;
        //将字符串数字转为整数
        for(int i=index;i<len;i++)
        {
            num=num*10+str[i]-'0';
        }
        index=len+1;
        //按先序创建二叉树
        auto root=new TreeNode(num);
        root->left=dfs2(str, index);
        root->right=dfs2(str,index);
        return root;
    }
};